package com.junxonline.plat.shiro;

import com.junxonline.plat.dao.SystemMenuDAO;
import com.junxonline.plat.model.SystemMenu;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author JunX
 * @ClassName: PermissionFilter
 * @Description: 权限过滤器
 */

@Component
public class PermissionFilter extends AccessControlFilter {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private SystemMenuDAO systemMenuDAO;

    /**
     * 权限认证
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return boolean
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {

        Subject subject = getSubject(servletRequest, servletResponse);

        if (null == subject || null == subject.getPrincipals()) {
            return Boolean.FALSE;
        }
        else {
            HttpServletRequest httpRequest = ((HttpServletRequest) servletRequest);
            // 获取URI
            String uri = httpRequest.getRequestURI();
            // 获取basePath
            String basePath = httpRequest.getContextPath();
            if (null != uri && uri.startsWith(basePath)) {
                uri = uri.replace(basePath, "");
                logger.info("permissionFilter拦截请求:" + uri);
            }

            SystemMenu systemMenu = systemMenuDAO.findByMenuUrl(uri);

            if (null != systemMenu && subject.isPermitted(systemMenu.getMenuPermission())) {
                return Boolean.TRUE;
            }
            response403(servletRequest, servletResponse);
            return Boolean.FALSE;
        }
    }

    /**
     * 认证失败
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return Boolean.FALSE;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /403
     */
    private void response403(ServletRequest req, ServletResponse resp) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
            httpServletResponse.sendRedirect("/403");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

}
